﻿using AutoMapper;
using B.S.BaseData.Domain;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Write.Api.Application.Command;
using MediatR;
using SqlSugar;

namespace B.S.BaseData.Write.Api.Application.CommandHander
{
    public class AddRoleMenuCommandHander : IRequestHandler<AddRoleMenuCommand, ApiResult<int>>
    {

        private readonly IMapper mapper;
        private readonly ISqlSugarClient db;

        public AddRoleMenuCommandHander(IMapper mapper, ISqlSugarClient db)
        {
            this.mapper = mapper;
            this.db = db;
        }

        /// <summary>
        /// 添加角色菜单处理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(AddRoleMenuCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();

            foreach (var item in request.MenuId)
            {
                var ur = new RoleMenu();
                ur.MenuId = item;
                ur.RoleId = request.RoleId;
                await db.Updateable<Role>(ur).ExecuteCommandAsync();
            }

            result.Code = ApiEnum.添加成功;
            result.Msg = ApiEnum.添加成功.ToString();
            return await Task.FromResult(result);
        }
    }
}
